var tableIns;
var searchParam = null;//用于存表单查询的条件参数
layui.use(['form','layer','laydate','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    //日期
    function getNowFormatDate() {
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = "'"+date.getFullYear() + "-" + month + "-" + strDate
            + " " + hours + ":" + minutes + ":" + seconds+"'";
        return currentdate;
    }
    var getNowFormatDate = getNowFormatDate();
    var dateMin = laydate.render({
        elem: '#regDateMin',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,//设置一个默认最大值
        done: function (value, dates) {
            dateMax.config.min ={
                year:dates.year,
                month:dates.month-1, //关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            };
        }
    });
    var dateMax = laydate.render({
        elem: '#regDateMax',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,
        done:function (value,dates) {
            dateMin.config.max={
                year:dates.year,
                month:dates.month-1,//关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            }
        }
    });
    var form = layui.form,
         layer=layui.layer;
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;

    tableIns = table.render({
        elem: '#defaultCustomerAnswerWayTable',
        url : baseUrl + '/flowConfig/queryDefaultCustomerAnswerWayPage',
        cellMinWidth : 95,
        height : "full-175",
        page : true,
        where:{
            flowId:"0",
            flowStepId:"0",
            doSearch:$("#doSearch").val()
        },
        request: {
            pageName: 'page' //页码的参数名称，默认：page
            ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            ,statusCode: 1 //成功的状态码，默认：0
            ,msgName: 'msg' //状态信息的字段名称，默认：msg
            ,countName: 'total' //数据总数的字段名称，默认：count
            ,dataName: 'records' //数据列表的字段名称，默认：data
        },loading: true
        ,page: {
            id:"id",
            limit: 10
            ,limits: [10, 20, 30, 40, 50]
            ,curr: 1
            ,groups: 5
            ,theme: '#5FB878'
            ,first: '首页'
            ,last: '尾页'
            ,prev: '<em><i class="layui-icon">&#xe603;</i></em>'
            ,next: '<em><i class="layui-icon">&#xe602;</i></em>'
            ,layout: [ 'prev', 'page', 'next', 'skip','count']
        },
        cols : [[
            {field: 'name', title: '分支名称', width:'20%',minWidth:120},
            {field: 'createUserName', title: '创建人', align:'center', width:'20%',minWidth:120},
            {field: 'modTime', title: '修改时间', align:'center', width:'30%',minWidth:150},
            {title: '操作', templet:'#customerAnswerWayListBar',fixed:"right",align:"center",width:'30%',minWidth:150}
        ]],done: function(res, curr, count){
            intTableColorChange();
        }
        ,text: {
            none: "false"==$("#doSearch").val()?'':'暂无相关数据'
            // none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        }
    });


    //列表操作
    table.on('tool(defaultCustomerAnswerWayTable)', function(obj){
        var layEvent = obj.event,
            param = obj.data;
        if(layEvent === 'edit'){ //编辑
            editCustomerAnswerWay(false,param.id);
        } else if(layEvent === 'del'){ //删除
            layer.confirm('您确定删除此默认回答方式？',{icon:3, title:'提示信息'},function(index){
                var load = layer.msg('执行中，请稍候',{icon: 16,time:false,shade:0.8});
                $.ajax({
                    type: "post",
                    url:  baseUrl+'/flowConfig/delCustomerAnswerWay?id='+param.id,
                    dataType: 'json',
                    success: function (data) {
                       layer.close(load);
                        if(data.code<=0){
                            layer.msg(data.msg);
                            layer.close(index);
                        }else{
                            reloadTable();
                            layer.close(index);
                        }
                    },
                    error: function () {
                        layer.close(load);
                        layer.msg("保存失败");
                        layer.close(index);
                    }
                });
            });
        }
    });


    // 提交查询条件表单
    form.on('submit(query)', function(data){
        searchParam = data.field;
        reloadTable();
    });

    //编辑默认分支
    function editCustomerAnswerWay(edit,id){
        var params = "?flowId=0&stepId=0&id="+id;
        currentIndex = layer.open({
            title : "新增分支",
            type : 2,
            content : [baseUrl+"/flowConfig/saveOrUpdateCustomerAnswerWay"+params],
            resize:true,
            maxmin:false,
            isOutAnim:true,
            scrollbar:true,
            area : ['80%','90%'],
            success : function(layero, index){
                var body = layer.getChildFrame('body', index);
                setTimeout(function(){
                    layer.tips('点击此处返回管理列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            },
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
                button.click();
                reloadTable();
            }
            , btn2: function (index, layero) {
                layer.close(index);
            }
        });
        setTimeout(function(){
            layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                tips: 3
            });
        },500);
        layui.layer.full(currentIndex);
    }
    $("#add_btn").click(function(){
        editCustomerAnswerWay(false,'0');
    });

    //选中行时，高亮显示
    function intTableColorChange(){
        $(".layui-table-body tr").click(function(e){
            $(".layui-table-body  tr ").css("background","");
            $(this).css("background","#e6e6e6");
        });
    }

});


//重新加载table的数据
function reloadTable() {
    var load = layer.load();
    var whereParam = {};
    if(searchParam!=null){
        whereParam = searchParam;
    }
    whereParam["flowId"] = "0";
    whereParam["flowStepId"] = "0";
    whereParam["doSearch"] = "true";
    tableIns.reload({
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: whereParam
    });
    layer.close(load);
}


/*
window.addEventListener('message', function(e)
{
    console.log('listen.....');
    var data = JSON.parse(e.data);
    if(data.key =="postUserMsg" && data.type == "SET"){
        console.log("Receive user info:"+data.value);//userId, roleId, userName,userNo,canSearchAll
        var postUserData = JSON.parse(data.value);
        if(postUserData){
            $("#createUserId").val(postUserData.userId);
            $("#canSearchAll").val(postUserData.canSearchAll);
            $("#query").click();
        }
    }
}, false);*/
